package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {

    }

    /**
     * 前置通知，再通知中进行公共字段赋值
     * @param joinPoint
     * @throws Exception
     */
    @Before("autoFillPointCut()")
    public void autoFillBefore(JoinPoint joinPoint) throws Exception {
        log.info("开始进行公共字段自动填充...");
        System.out.println(joinPoint);

        // MethodSignature 是 Spring AOP 提供的一个接口，表示你当前拦截到的方法的“签名信息”
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = annotation.value();

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object object = args[0];
        // 准备数据
        LocalDateTime now = LocalDateTime.now();
        Long  userId = BaseContext.getCurrentId();

        Method  SET_UPDATE_TIME = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
        Method  SET_UPDATE_USER = object.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
        SET_UPDATE_TIME.invoke(object, now);
        SET_UPDATE_USER.invoke(object, userId);

        if (operationType == OperationType.INSERT) {
            Method  SET_CREATE_TIME = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method  SET_CREATE_USER = object.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            SET_CREATE_TIME.invoke(object, now);
            SET_CREATE_USER.invoke(object, userId);
        }
    }
}
